package com.kakarote.hrm.utils;


import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 * @Author 92487
 * @Date 2024/3/13 20:51
 */

public class HttpUtils {

    //接口密钥
    private final static String SHAREKEY = "94B70F01C2646F0FCA72A3332C8ACEFCE80C8B50BCA3F8020428365A978B806D";
//    private final static String SHAREKEY = "57FE6FF4F535E225AB056E62221F39416FFA05C8F6C2AB21DDD72DA16799A2CC";
    //资源编码
    private final static String APPID = "hrm";
//    private final static String APPID = "oa";

    /**
     * <p>创建http请求接口
     */
    public static String createGetHttp(String url, Map<String, String> params) {
        String result = "";
        CloseableHttpClient httpClient = null;
        // 创建HttpGet
        HttpGet httpget = null;
        CloseableHttpResponse response = null;
        try {
            // 构建查询字符串
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (sb.length() > 0) {
                    sb.append("&");
                }
                sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                sb.append("=");
                sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            if (sb.length() > 0 ){
                url = url + "?" + sb.toString();
            }
            httpClient = HttpClients.createDefault();
            httpget = new HttpGet(url);
            //获取时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            String token = getToken(SHAREKEY, APPID, timestamp);
            httpget.setHeader("timestamp", timestamp);
            httpget.setHeader("token", token);
            httpget.setHeader("appid", APPID);

            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(60000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            httpget.setConfig(requestConfig);

            response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            result = e.getMessage();
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接,释放资源
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * <p>创建http请求接口
     */
    public static String createPostHttp(String url, Map<String, String> headers) {
        String result = "";
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<>();
            if (headers != null && headers.size() != 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    params.add(new NameValuePair() {
                        @Override
                        public String getName() {
                            return entry.getKey();
                        }

                        @Override
                        public String getValue() {
                            return entry.getValue();
                        }
                    });
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            //获取时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            String token = getToken(SHAREKEY, APPID, timestamp);
            httpPost.setHeader("timestamp", timestamp);
            httpPost.setHeader("token", token);
            httpPost.setHeader("appid", APPID);
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(30000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            httpPost.setConfig(requestConfig);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
        } catch (Exception e) {
            HashMap<String, String> map = new HashMap<>();
            map.put("msg",e.getMessage());
            result = JSON.toJSONString(map);
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接,释放资源
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * <p>生成token
     *
     * @param sharekey  共享密码
     * @param appid     资源编码
     * @param timestamp 时间戳
     * @return
     */
    private static String getToken(String sharekey, String appid, String timestamp) {
        Sha256 sha256 = new Sha256();
        //SM3 sm3 = new SM3();
        String temp = sharekey + appid + timestamp;
        String token = sha256.encrypt(temp);
        return token;
    }

//    public static void main(String[] args) {
//        String timestamp = String.valueOf(System.currentTimeMillis());
//        String token = getToken(SHAREKEY, APPID, timestamp);
//        System.out.println(timestamp);
//        System.out.println(token);
//    }
}
